using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using SharpCast;
using System.Threading;

namespace mmPodcasts
{
    public partial class NewChannelDialog : Form
    {
        private Channel channel;

        public NewChannelDialog()
        {
            InitializeComponent();

            if (Clipboard.ContainsText() && Clipboard.GetText().StartsWith("http"))
            {
                feedURL.Text = Clipboard.GetText();
            }
        }

        internal Channel getChannel()
        {
            return channel;
        }

        private void verifyButton_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            verifyButton.Enabled = false;
            ThreadStart s = new ThreadStart(verifyPodcast);
            new Thread(s).Start();
        }

        private void verifyPodcast()
        {
            Control.CheckForIllegalCrossThreadCalls = false;
            try
            {
                channel = new Channel();
                List<Exception> errors = channel.load(feedURL.Text);
                if (channel.title != null)
                {
                    desc.Text = "Podcast verified: " + channel.title;
                    desc.Text += "\n" + channel.episodes.Length + " episodes available";
                    foreach (Exception e in errors)
                    {
                        desc.Text += "\nError: " + e.Message + "\n" + e.StackTrace; 
                    }
                    addButton.Enabled = true;
                    return;
                }
            }
            catch (Exception e2)
            {
                desc.Text = "Unable to load podcast: " + e2.Message + "\n" + e2.StackTrace;
            }
            finally
            {
                Cursor = Cursors.Arrow;
                verifyButton.Enabled = true;
                Control.CheckForIllegalCrossThreadCalls = true;
            }
            channel = null;
            addButton.Enabled = false;
        }

        private void addButton_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.OK;
            if (channel != null)
            {
                Close();
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            Close();
        }
    }
}